// page/index/index.js
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfos: {},
    itemsone: [{
      locationId: '1',
      locationName: '一工厂',
      locationType: '1'
    }],
    wxId:"",
    jimo: '123',
    appid: 'wx431a80e5cb7ad48f',
    secretid: 'f9d6ccc8dcd5f30452a316452ba35c33',
    imageArr: [],
    locationIdSum: [],
    locationIdTypeOne: [],
    locationIdTypeTwo: [],
    locationId: [
      [1],
      [2],
      [3]
    ],
    details: null,
    locationString: "",
    sum: 0, //做多选框计数，现已废弃
    oneYear: "yes"
  },


  

  //分割
  SplicingLocationId() {
    let locaID = "";
    var a = 0;
    for (var index in this.data.locationIdSum) {
      a = index;
      if (++a == this.data.locationIdSum.length) {
        locaID += this.data.locationIdSum[index]
      } else {
        locaID += this.data.locationIdSum[index] + ","
      }
      this.setData({
        locationString: locaID
      })
    }
    if (this.data.locationIdSum == 0) {
      this.setData({
        locationString: ""
      })
    }
  },
  //位置type1
  checkboxChangeone(e) {
    this.setData({
      locationIdTypeOne: e.detail.value
    })
    let location = this.data.locationIdTypeTwo
    location = location.concat(this.data.locationIdTypeOne)
    this.setData({
      locationIdSum: location
    })
    this.SplicingLocationId();
  },
  //位置type2
  checkboxChangetwo(e) {
    this.setData({
      locationIdTypeTwo: e.detail.value
    })
    let location = this.data.locationIdTypeOne
    location = location.concat(this.data.locationIdTypeTwo)
    this.setData({
      locationIdSum: location
    })
    this.SplicingLocationId();
  },


  inputChange(e) {

    if (e.target.dataset.type == 'details') {
      //细部描述设置
      this.setData({
        details: e.detail.value
      })
    } else if (e.target.dataset.type == 'username') {
      //联系人设置
      var userContacts = "userInfos[0].userContacts";
      this.setData({
        [userContacts]: e.detail.value
      })
    } else if (e.target.dataset.type == 'phone') {
      //手机号码设置
      var userPhone = "userInfos[0].userPhone";
      this.setData({
        [userPhone]: e.detail.value
      })
      console.log(this.data.userInfos[0].userPhone)
    }

  },

  //显示图片
  onuploadImage() {
    wx.chooseImage({
      success: (res) => {
        let images = this.data.imageArr;
        this.setData({
          imageArr: images.concat(res.tempFilePaths)
        })
      },
    })
  },

  //移除图片
  removeImage(event) {
    let images = this.data.imageArr;
    //检查是否删除正确
    let imageaddress = images[event.target.dataset.imageindex];
    images.splice(event.target.dataset.imageindex, 1)
    if (imageaddress == images[event.target.dataset.imageindex - 1]) {
      console.log("删除错误");
    } else {
      console.log("删除成功");
    }
    //删除完赋值
    this.setData({
      imageArr: images
    })
  },

  //预览图片
  previewImg(e) {
    wx.previewImage({
      current: this.data.imageArr[e.target.dataset.imageindex], // 当前显示图片的http链接
      urls: this.data.imageArr // 需要预览的图片http链接列表
    })
  },
  //提交
  submitReport() {
    var i = 0;
    var flag = false;
    wx.showLoading({
      title: '图片正在上传中',
    })
    for (var index in this.data.imageArr) {
      flag = true;
      wx.uploadFile({
        url: 'https://www.hankooktire-wx.com.cn:8443/htwx-api/UserController/upload', //仅为示例，非真实的接口地址
        filePath: this.data.imageArr[index],
        name: 'files',
        formData: {

        },
        success: (res) => {
          let data = res.data
          var a = index;
          console.log("a:", ++a)
          console.log("i:", i)
          if (a === ++i) {
            this.submitText();
          }
       
          //do something
        }
      })
    }
    if (flag != true) {
      console.log("进入无图片提交")
      this.submitText();
    }
  },
  //报表信息提交
  submitText() {
    wx.request({
      url: 'https://www.hankooktire-wx.com.cn:8443/htwx-api/UserController/insertReport',
      data: {
        locationId: this.data.locationString,
        wxId: this.data.userInfos[0].wxId,
        details: this.data.details,
        whether_repair: this.data.oneYear
      },
      method: 'GET',
      dataType: 'json',
      success: (state) => {
        console.log("报表信息状态:", state)
        this.setData({
          imageArr: [],
          locationIdSum: [],
          locationIdTypeOne: [],
          locationIdTypeTwo: [],
          itemsone: this.data.itemsone,
          details: null,
          locationString: "",
        })
        wx.hideLoading();
        wx.showToast({
          title: "提交完成",
          icon: 'none',
        })
      }
    })
    app.sendWebsocket(this.data.userInfos);
  },

  onRadio(e) {
    console.log("保质期：", e);
    console.log("保质期的值：", e.detail.value);
    this.setData({
      oneYear: e.detail.value
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
      wx.showModal({
        title: '提示',
        content: '请问确定要登陆吗？这将会获取你的账号信息',
        success: (res) => {
          if (res.confirm) {
            this.htLogin();
          } else if (res.cancel) {
            wx.navigateTo({
              url: '../out/out',
            })
          }
        }
      })  
  },

  htLogin(){
    app.onSocketMessage(this);
    wx.login({
      success: (datas) => {
        //请求openid
        wx.request({
          url: 'http://localhost:8080/UserController/logincheck',
          data: {
            appid: this.data.appid,
            secretid: this.data.secretid,
            jscode: datas.code,
            // grant_type: 'authorization_code'
          },
          header: {},
          method: 'GET',
          dataType: 'json',
          responseType: 'text',
          //请求成功
          success: (ress) => {
            this.setData({
              wxId: ress.data.openid
            })
            app.globalData.userWxId = this.data.wxId
            //获取当前用户信息
            wx.request({
              url: 'https://www.hankooktire-wx.com.cn:8443/htwx-api/UserController/getUserById',
              data: {
                wxId: ress.data.openid
              },
              header: {
                'content-type': 'application/json'
              },
              method: 'get',
              dataType: 'json',
              responseType: 'text',
              success: (userinfo) => {
                if (userinfo.data.length > 0) {
                  this.setData({
                    userInfos: userinfo.data
                  })
                  console.log("userContacts", this.data.userInfos[0].userContacts)
                  app.globalData.username = this.data.userInfos[0].userContacts
                  app.globalData.user = this.data.userInfos[0];
                  app.connectsocket(userinfo.data);
                } else {
                  console.log("忽略用户信息")
                  wx.request({
                    url: "https://www.hankooktire-wx.com.cn:8443/htwx-api/UserController/insertUser",
                    data: {
                      wxId: this.data.wxId
                    },
                    method: "get",
                    success: (d) => {
                      console.log("d:", d)
                      this.onLoad();
                    }
                  })
                }


              },
              fail: function (res) {
                console.log("no");
              },
              complete: function (res) { },
            })


          },
          fail: function (res) { },
          complete: function (res) { },
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    //请求工厂信息
    this.getFactroy();
  },
  //请求工厂信息
  getFactroy() {
    wx.request({
      url: 'https://www.hankooktire-wx.com.cn:8443/htwx-api/UserController/getFactorylocationAll',
      data: {},
      header: {
        'content-type': 'application/json'
      },
      method: 'get',
      dataType: 'json',
      success: (res) => {
        this.setData({
          itemsone: res.data
        })
      },
      fail: function(res) {
        console.log("no");
      },
      complete: function(res) {},
    })
  },


  /** 
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (this.data.userInfos.length > 0) {
      wx.request({
        url: 'https://www.hankooktire-wx.com.cn:8443/htwx-api/UserController/getUserById',
        data: {
          wxId: this.data.userInfos[0].wxId
        },
        success: (userinfo) => {
          console.log("userinfo:", userinfo);
          this.setData({
            userInfos: userinfo.data
          })
        }
      })
    }
  },




  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.showNavigationBarLoading();
    this.getFactroy();
    wx.stopPullDownRefresh();
    wx.hideNavigationBarLoading();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})